package jym.tan.movielibrary.factory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import jym.tan.movielibrary.configuration.ui.UIProperties;
import jym.tan.movielibrary.constant.GlobalConstant;
import jym.tan.movielibrary.logger.LibraryLogger;

public class FileFactory {

	public static void createHomeDirectory() {
		String pathToHome = GlobalConstant.MOVIE_LIBRARY_HOME;
		File home = new File(pathToHome);
		if(home.exists()) {
			return;
		}
		home.mkdir();
		LibraryLogger.infoMessage("Movie Library Home Folder Does Not Exists. Created.");
	}
	
	public static void createSerDirectory() {
		createHomeDirectory();
		String pathToSer = GlobalConstant.MOVIE_LIBRARY_SER;
		File ser = new File(pathToSer);
		if(ser.exists()) {
			return;
		}
		ser.mkdir();
		LibraryLogger.infoMessage("Ser Folder Does Not Exists. Created.");
	}
	
	public static void createUIProperties(UIProperties properties) throws FileNotFoundException, IOException {
		createSerDirectory();
		LibraryLogger.infoMessage("UIProperties File Does Not Exists. Created.");
		writeObject(properties, GlobalConstant.MOVIE_LIBRARY_SER + GlobalConstant.FILE_SEPARATOR);
	}
	
	public static void saveUIProperties(UIProperties uiProperties) throws FileNotFoundException, IOException {
		writeObject(uiProperties, GlobalConstant.MOVIE_LIBRARY_SER + GlobalConstant.FILE_SEPARATOR);
	}
	
	public static <T> void writeObject(T t, String path) throws FileNotFoundException, IOException{
		ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(new File(path + t.getClass().getSimpleName() + GlobalConstant.SER_EXTENTION)));
		stream.writeObject(t);		
		stream.close();
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T readObject(Class<T> clazz, String path) throws FileNotFoundException, IOException, ClassNotFoundException {
		ObjectInputStream stream = new ObjectInputStream(new FileInputStream(new File(path + clazz.getSimpleName() + GlobalConstant.SER_EXTENTION)));
		return (T)stream.readObject();
	}
	
	public static UIProperties getUIProperties() throws FileNotFoundException, IOException, ClassNotFoundException {
		return readObject(UIProperties.class, GlobalConstant.MOVIE_LIBRARY_SER + GlobalConstant.FILE_SEPARATOR);
	}
	
	public static boolean isUIPropertiesExists() {
		return isSerExists(UIProperties.class);
	}
	
	public static <T> boolean isSerExists(Class<T> clazz) {
		return new File(GlobalConstant.MOVIE_LIBRARY_SER + GlobalConstant.FILE_SEPARATOR + clazz.getSimpleName() + GlobalConstant.SER_EXTENTION).exists();
	}
}
